﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace TinySocket
{
    class Server
    {
        Socket listener;

        Thread listenerThread;

        public void StartListening(string ipString, int port)
        {
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Parse(ipString), port));
            listener.Listen(0);

            listenerThread = new Thread(ListenThreadFunc);
            listenerThread.IsBackground = true;
            listenerThread.Start();
        }

        public void StopListening()
        {
            SocketExtensions.CloseSocket(listener);
            listenerThread.Join();

            listener = null;
            listenerThread = null;
        }

        void ListenThreadFunc(object state)
        {
            try
            {
                while (true)
                {
                    Socket socket = listener.Accept();

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
    }
}
